﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Inscriptionem.Localization;
using Inscriptionem.MVC;
using Inscriptionem.Services;

namespace Inscriptionem
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        protected void Application_Start()
        {
            RegisterGlobalFilters(GlobalFilters.Filters);

            // Bind checkbox model binder
            ModelBinders.Binders.Add(typeof (bool), new CheckedModelBinder());

            // Set LocalizableViewEngine
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new LocalizableViewEngine());

            RegisterRoutes();
        }

        public static void RegisterRoutes()
        {
            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            if (InstallService.IsDBAvailableAndCorrect)
            {
                AreaRegistration.RegisterAllAreas();
                RegisterRegularRoutes(RouteTable.Routes);
            }
            else
            {
                RegisterInstallRoutes(RouteTable.Routes);
            }
        }

        private static void RegisterRegularRoutes(RouteCollection routes)
        {
            routes.Add(new RegexRoute("(?<language>([^/]*))(/*)(?<controller>Login)(/*)(?<action>([^/]*))(/*)(?<id>([^/]*))",
                                      new {language = Language.DefaultValue, controller = "Login", action = "Index", id = UrlParameter.Optional}));

            routes.Add(new RegexRoute("(?<language>([^/]*))(/*)(?<controller>Member)(/*)(?<action>([^/]*))(/*)(?<id>([^/]*))",
                                      new {language = Language.DefaultValue, controller = "Member", action = "Index", id = UrlParameter.Optional})
                           {
                               Namespaces = new string[] {"Inscriptionem.Controllers"} // Fix for looking for Member controller in Inscriptionem area
                           });

            routes.Add(new RegexRoute("(?<language>([^/]*))(/*)(?<controller>Contact)(/*)(?<action>([^/]*))(/*)(?<id>([^/]*))",
                                      new {language = Language.DefaultValue, controller = "Contact", action = "Index", id = UrlParameter.Optional})
                           {
                               Namespaces = new string[] {"Inscriptionem.Controllers"} // Fix for looking for Member controller in Inscriptionem area
                           });

            routes.Add(new RegexRoute("(?<language>([^/]*))(/*)(?<section>([^/]*))(/*)(?<action>([^/]*))(/*)(?<id>([^/]*))(/*)(?<navigation>([^/]*))",
                                      new {language = Language.DefaultValue, section = "", controller = "Blog", action = "Index", id = UrlParameter.Optional, navigation = UrlParameter.Optional}));
        }

        private static void RegisterInstallRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "Install", // Route name
                "Inscriptionem/{action}/{id}", // URL with parameters
                new {controller = "Install", action = "Index", id = UrlParameter.Optional} // Parameter defaultsW
                );

            routes.MapRoute(
                "Maintenance", // Route name
                "{*path}", // URL with parameters
                new { controller = "Install", action = "Maintenance", path = UrlParameter.Optional } // Parameter defaults
                );
        }

        protected void Application_Error()
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            Response.Clear();
            Server.ClearError();

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Index";
            routeData.Values["exception"] = exception;

            Response.StatusCode = 500;
            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                    //case 403:
                    //    routeData.Values["action"] = "Http403";
                    //    break;
                    case 404:
                        routeData.Values["action"] = "Http404";
                        break;
                }
            }

            // Avoid IIS7 getting in the middle
            Response.TrySkipIisCustomErrors = true;
            IController errorsController = new Controllers.ErrorController();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            var rc = new RequestContext(wrapper, routeData);
            errorsController.Execute(rc);
        }
    }
}